package csm.common.security;

import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;

import csm.common.StringUtil;

/**
 * DESede 암호화/복호화 처리 클래스
 * @author seungmun
 * @since 2006.1.18.
 *
 */
public class DESSimpleCryptography
{
	private final static String ALGORITHM = "DESede";
	@SuppressWarnings("unused")
    private final static int KEY_LENGTH = 168;
	private final static String PADDING = "DESede/ECB/PKCS5Padding";



	/**
	 *
	 * @param string
	 * @param key
	 * @return
	 * @throws NoSuchPaddingException
	 * @throws NoSuchAlgorithmException
	 * @throws Exception
	 */
	public static String encrypt(String string, String key) throws Exception
	{

		Cipher cipher = Cipher.getInstance(PADDING); // 모드 설정
		cipher.init(Cipher.ENCRYPT_MODE, makeKey(key));

		byte[] plainText = string.getBytes("UTF8");

		// 암호화 시작
		byte[] cipherText = cipher.doFinal(plainText);

		return Base64Encoder.encode(cipherText);
	}

	public static String decrypt(String cipherText, String key) throws Exception
	{
		// 복호화 모드로서 초기화
		Cipher cipher = Cipher.getInstance(PADDING); // String으로 모드 설정
		cipher.init(Cipher.DECRYPT_MODE, makeKey(key));

		// 복호화 수행
		byte[] decryptedText = cipher.doFinal(Base64Encoder.decode(cipherText));
		String output = new String(decryptedText, "UTF8");
		return output;
	}

	/**
	 * 암호화 키/복호화 키(24Byte)
	 *
	 * @param key
	 * @return
	 * @throws Exception
	 */
	private static SecretKey makeKey(String key) throws Exception
	{
		if (key == null || key.length() < 24)
			key = StringUtil.padr(key, 24, 'x');

		if( key.length() >24 )
		    throw new Exception("invalid [key] length");

		byte[] keydata = key.getBytes();

		DESedeKeySpec keySpec = new DESedeKeySpec(keydata);
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);

		SecretKey desKey = keyFactory.generateSecret(keySpec);
		return desKey;
	}

	public static void main(String[] args)
	{
		try
		{
			String data = DESSimpleCryptography.encrypt("12345678", "abcdefg");
			System.out.println(data);
			data = DESSimpleCryptography.decrypt(data, "abcdefg");
			System.out.println(data);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}
